//
//  WCNMeVC.m
//  WCN
//
//  Created by 杨鑫 on 15/5/31.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMeVC.h"
#import "WCNMeEditVC.h"
#import "WCNMeSettingVC.h"
#import "WCNMeCommentsVC.h"
#import "WCNPastPaientsVC.h"
#import "WCNMulTextEditVC.h"
#import "WCNLoginVC.h"
//
#import "WCNIconLabelTCell.h"
//
#import "WCImgBrowserView.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
//

#import "WCNSettingItemController.h"
#import "WCNMyMessageVC.h"
//#import "WCNNavigationController.h"
#import "WCNTabBarVC.h"
//#import "ChatManager.h"
#import "WCNServiceTimePageVC.h"
#import "WCImageView +setImage.h"
//#import "WCConversationVC.h"
#import "WCAccessoryView.h"
//#import "WCHuanxinToolByWsj.h"
#import "WCButtonForNoti.h"
#import "cwqMessageTypesVC.h"
#import "WCPopupLayerManager.h"
#import "WCRegisterViewController.h"
#import "WCBPushToolByWsj.h"
#import "WCImageView +setImage.h"
#import "WCNSubSettingVC.h"
#import <YTXAnimations/UIView+YTXAnimateCSS.h>
#import "WCNotifyMessageListVC.h"

static NSString *cellId = @"WCNIconLabelTCell";

@interface WCNMeVC () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, WCImgBrowserViewDelegate>
{
    NSInteger _nurseId;
    
}


@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (strong, nonatomic) UITapGestureRecognizer *tapRecognizer;
@property (weak, nonatomic) IBOutlet UILabel *idLabel;

@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *avgScore;
@property (weak, nonatomic) IBOutlet UILabel *totals;
@property (weak, nonatomic) IBOutlet UILabel *scoreTime;
@property (weak, nonatomic) IBOutlet UILabel *scoreTaidu;
@property (weak, nonatomic) IBOutlet UILabel *scoreZY;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *showAccountInfoButton;
/**
 *  二维码图片
 */
@property (weak, nonatomic) IBOutlet UIImageView *QRCodeImageView;
@property (nonatomic, retain) NSArray *titleArray;;


@property (strong, nonatomic) NSString *url;

@property (nonatomic, strong) WCButtonForNoti *notiBtn;

@end

@implementation WCNMeVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"我";
        //        [self registerNotifications];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:self.notiBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    self.avatar.layer.cornerRadius = 30;
    self.avatar.clipsToBounds = YES;
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
}
- (WCButtonForNoti *)notiBtn{
    if (_notiBtn ==nil) {
        _notiBtn =[[WCButtonForNoti alloc] initWithFrame:CGRectMake(kScreenWidth -35 -20, 24, 30, 30) withBtnImage:@"铃铛.jpg"];
        _notiBtn.notices = 100;
        weakSelf_define;
        _notiBtn.pressBlock= ^(){
            
            WCNotifyMessageListVC *vc =[[WCNotifyMessageListVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        };
        
        
        
    }
    return _notiBtn;
    
}
#pragma mark -注册信息处理代理
//-(void)registerNotifications
//{
//    [self unregisterNotifications];
//
//    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
//    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
//}
//-(void)unregisterNotifications
//{
//    [[EaseMob sharedInstance].chatManager removeDelegate:self];
//    [[EaseMob sharedInstance].callManager removeDelegate:self];
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.QRCodeImageView ytx_zoomInRightAnimtionWithDurationTime:2];
    
    [self.avatar ytx_rotateInAnimtionWithDurationTime:2];
    [self.notiBtn  ytx_rubberBandAnimtionWithDurationTime:1];
    
    //
    Account *account = [[WCDefaultManager shareMg] account];
    if (!account) {
        return;
    }
    _nurseId =[account.stringId integerValue];
    self.name.text = account.name;
    if (account.qrCode) {
        
        NSString *url = [[UIImageView getimageUrlForMedia] stringByAppendingString:account.qrCode];
        [self.QRCodeImageView setImageWithURL:[NSURL URLWithString:url]];
    }
    self.idLabel.text = [NSString stringWithFormat:@"ID:%@",account.stringId];
    //获取一下是否有群 唯独消息
    if (self.tableView) {
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2
                                                                    inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    
    
    
    
    
    NSString *accountInfoUrlString = [NSString stringWithFormat:@"nurse/account/%@",account.stringId];
    
    //    if ([[WCNetworkAccessManager sharedMg] timeSinceLastUrl:accountInfoUrlString] > kUrlCD/10) {
    self.showAccountInfoButton.enabled = NO;
    [[WCNetworkAccessManager sharedMg] GET:accountInfoUrlString parameters:nil success:^(NSDictionary *result){
        if ([result[@"success"] integerValue] == 1) {
            self.name.text = result[@"data"][@"name"];
            [[WCDefaultManager shareMg] updateAccountWithDic:result[@"data"]];
        }
    } failure:nil netError:nil always:^{
        self.showAccountInfoButton.enabled = YES;
    }];
    
    
    self.url = [NSString stringWithFormat:@"nurse/stat/%@", account.stringId];
    
    [self showData];
    [self getNotifyMessageCount];
    
}


- (NSArray *)titleArray
{
    if (_titleArray ==nil) {
        _titleArray = @[@"设置",@"服务评价",@"留言咨询",@"意见反馈",@"客服电话",@"修改密码"];
    }
    return _titleArray;
    
}
- (void)showData
{
    Account *account = [[WCDefaultManager shareMg] account];
    AccountStat *stat = [[WCCoreDataStore shareStore] getAccountStat];
    
    self.avgScore.text = [NSString stringWithFormat:@"综合评分:%.1f", stat.avgRatingGeneral];
    self.totals.text = [NSString stringWithFormat:@"%d单", stat.orderCount];
    self.scoreZY.text = [NSString stringWithFormat:@"守时:%.1f", stat.avgRatingPunctuality];
    self.scoreTaidu.text = [NSString stringWithFormat:@"态度:%.1f", stat.avgRatingAttitude];
    self.scoreTime.text = [NSString stringWithFormat:@"专业:%.1f", stat.avgRatingExpertise];
    
    
    
    
    [[WCNetworkAccessManager sharedMg] GET:self.url parameters:nil success:^(NSDictionary *result){
        AccountStat *stat = [[WCCoreDataStore shareStore] updateAccountStat:result[@"data"]];
        
        self.avgScore.text = [NSString stringWithFormat:@"综合评分:%.1f", stat.avgRatingGeneral];
        self.totals.text = [NSString stringWithFormat:@"%d单", stat.orderCount];
        self.scoreZY.text = [NSString stringWithFormat:@"守时:%.1f", stat.avgRatingPunctuality];
        self.scoreTaidu.text = [NSString stringWithFormat:@"态度:%.1f", stat.avgRatingAttitude];
        self.scoreTime.text = [NSString stringWithFormat:@"专业:%.1f", stat.avgRatingExpertise];
    } failure:nil netError:nil always:nil];
    
    [[WCImageManager sharedMg] downloadImage:account.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
        self.avatar.image = image;
    } failure:nil];
}

- (void)showBigAvatar:(id)sender {
    WCImgBrowserView *imgBrowser = [[WCImgBrowserView alloc] initWithFrame:self.navigationController.view.bounds];
    imgBrowser.delegate = self;
    [self.navigationController.view addSubview:imgBrowser];
}
#pragma mark -请求站内消息未读数
- (void)getNotifyMessageCount{
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimpleInImageView:self.notiBtn];
    //    "targetId": 86,
    //    "targetType": 1
    NSInteger targetId =[[[[WCDefaultManager shareMg] account] stringId] integerValue];
    NSDictionary *params =@{@"targetId":@(targetId),@"targetType":@(1)};
    weakSelf_define;
    [[WCNetworkAccessManager sharedMg] POST:kNotifyMessageCount parameters:params success:^(NSDictionary * responseObject) {
        NSInteger num =[responseObject[@"data"] integerValue];
        if (num && num>0) {
            [WCBPushToolByWsj saveNewBadge:num];
            weakSelf.notiBtn.notices = num;
        }else{
            [WCBPushToolByWsj saveNewBadge:0];
            weakSelf.notiBtn.notices = 0;
            
        }
        
        
    } failure:nil netError:nil always:^{
        [hud hide:YES];
        
    }];
    
    
}

#pragma mark - Nib Targets

- (IBAction)showMeEditVC:(id)sender {
    WCNMeEditVC *vc = [[WCNMeEditVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCNIconLabelTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.iconTitle.text = self.titleArray[indexPath.row];
    cell.accessoryView =nil;
    switch (indexPath.row) {
        case 0:{
            cell.leftIcon.image = [UIImage imageNamed:@"Me_Set"];
            //            cell.iconTitle.text = @"服务设置";
            break;
        }
        case 1:{
            cell.leftIcon.image = [UIImage imageNamed:@"Me_eval"];
            //            cell.iconTitle.text = @"服务评价";
            break;
        }
        case 2:{
            cell.leftIcon.image = [UIImage imageNamed:@"Me_patient"];
            //            cell.iconTitle.text = @"留言咨询";
            break;
        }
        case 3:{
            cell.leftIcon.image = [UIImage imageNamed:@"Me_feedback"];
            //            cell.iconTitle.text = @"意见反馈";
            break;
        }case 4:{
            cell.leftIcon.image = [UIImage imageNamed:@"客服电话"];
            //            cell.iconTitle.text = @"客服电话";
            break;
        }
        case 5:{
            cell.leftIcon.image = [UIImage imageNamed:@"修改密码"];
            //            cell.iconTitle.text = @"客服电话";
            break;
        }
        case 6:{
            cell.leftIcon.image = [UIImage imageNamed:@"退出登录"];
            //            cell.iconTitle.text = @"客服电话";
            break;
        }
            
            
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0:{
            //服务设置
            
            
            [self.navigationController pushViewController:[WCNSubSettingVC new] animated:YES];
            break;
        }
        case 1:{
            
            
            WCNMeCommentsVC *vc = [[WCNMeCommentsVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 2:{
            WCNMyMessageVC *vc =[[WCNMyMessageVC alloc]init];
            vc.nurseId =_nurseId;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 3:{
            WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSend];
            vc.title = @"意见反馈";
            vc.textViewPlaceholder = @"请填写意见反馈";
            vc.url = @"feedback/add";
            
            Account *account = [[WCDefaultManager shareMg] account];
            vc.params = [NSMutableDictionary dictionaryWithDictionary:@{@"userId":account.stringId, @"content":@"", @"attachpics":@""}];
            
            vc.paramKey = @"content";
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 4:{
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"4001009630"];
            //            NSLog(@"str======%@",str);
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            
            
            break;
        }
            
        case 5:{
            
            WCRegisterViewController *vc =[WCRegisterViewController new];
            [vc setViewController:WCViewControllerModeMotifyPassword];
            [self.navigationController pushViewController:vc animated:YES];
            
            break;
        }
            
            
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

#pragma mark - WCImgBrowserViewDelegate

- (UIImageView *)viewOfBrowserViewshowFrom
{
    return self.avatar;
}

- (UIImageView *)viewOfBrowserViewRemoveToAtIndex:(NSInteger)index
{
    return self.avatar;
}

- (NSInteger)numberOfImagesInBrowserView
{
    return 1;
}

- (NSString *)browserItemIdForItemAtIndex:(NSInteger)index
{
    return [[WCDefaultManager shareMg] account].stringId;
}

- (WCImageType)browserItemTypeForItemAtIndex:(NSInteger)index
{
    return WCImageTypeNurse;
}

- (NSInteger)indexForFirstShow
{
    return 0;
}
//#pragma mark -收到新消息的代理方法
//- (void)didReceiveMessage:(EMMessage *)message{
//
//    //新消息如果是群组的刷新改行cell
//    if (message.messageType ==eMessageTypeGroupChat) {
//        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2
//                                                                    inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
//
//    }
//
//}
//#pragma mark -唯独消息改变的时候
//
//- (void)didUnreadMessagesCountChanged{
//
//    if ([WCHuanxinToolByWsj getGroupUnreadMessageAccout]>0) {
//        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2
//                                                                    inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
//    }
//
//
//}
@end
